package bday.tvlport.scheduler;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;

import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import bday.tvlport.db.DbConnection;
import bday.tvlport.mail.SendMailTLS;
import bday.tvlport.models.UserDetails;
import bday.tvlport.utils.DobUtils;
import bday.tvlport.utils.LoggerUtility;

public class MailingJob implements Job {

	/** Creates a new instance of SimpleQuartzJob */
	public MailingJob() {
	}

	public void execute(JobExecutionContext context)
			throws JobExecutionException {
		try {
			MongoOperations mongoOperations = DbConnection.getMongo();
			if(mongoOperations != null) {
				LoggerUtility.info("Sorting started");
				Query searchUserQuery = new Query(Criteria.where("dobMonthDate").is(DobUtils.getMonthDate(new Date())));
				
				List<UserDetails> savedUsers = mongoOperations.find(searchUserQuery, UserDetails.class);
				LoggerUtility.info("Match found: " + savedUsers.size());
				if(!CollectionUtils.isEmpty(savedUsers)) {
					List<String> mailToList = new ArrayList<String>();
					List<String> names = new ArrayList<String>(); 
					for (UserDetails user : savedUsers) {
						mailToList.add(user.getEmail()); 
						names.add(user.getName());
					}
					SendMailTLS.mail(StringUtils.collectionToCommaDelimitedString(mailToList), getMessageBody(names), false);
				}
			}
		} catch (Throwable e) {
			LoggerUtility.error(e.toString());
		}
	}
	
	private String getMessageBody (List<String> names) {
		Collections.sort(names);
		String body = "Happy birthday\n\n";
		for(int i = 1; i<names.size()+1;i++) {
			body+= i +". " + names.get(i-1) + "\n";
		}
		return body + "\nWish you many many happy returns of the day.\n\nRegards,\nYour Team";
	}
}
